/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package simple;

import algorithm.AlgorithmErrorException;
import algorithm.Environment;
import algorithm.Genotype;
import algorithm.Individual;
import algorithm.Population;
import algorithm.PopulationBreeder;

/**
 *
 * @author vermaak
 */
public class MutationBreeder implements PopulationBreeder {

    private double chancePerIndividual;
    private double fractionOfGenotypeToMutate;
    private transient BitStringMutationOperator operator;

    public MutationBreeder(double chancePerIndividual, double fractionToMutate) {
        this.chancePerIndividual = chancePerIndividual;
        this.fractionOfGenotypeToMutate = fractionToMutate;

        operator = new BitStringMutationOperator(fractionToMutate);
    }

    public Population createNewPopulation(Population population1, Population population2, Environment environment, int size) throws AlgorithmErrorException {
        if (population2 != null) {
            throw new AlgorithmErrorException("Operates on a single populatio only. Set the other null");
        }
        Population ret = Factory.createPopulation(population1.getClass());

        for (int i = 0; i < size; ++i) {
            Individual currentInd = population1.getIndividual(i);
            Genotype genotype = currentInd.getGenotype();
            double roll = Math.random();
            if (roll <= chancePerIndividual) {
                Individual newInd = operator.operate(currentInd);
                ret.add(newInd);
            } else {
                ret.add(currentInd);
            }
        }
        return ret;
    }
}
